'use strict';
module.exports = ({ mongoose }) => {
  const Schema = new mongoose.Schema({
    ip: String,
    url: String,
    origin: String,
  }, {
    timestamps: {
      createdAt: 'createdAt',
    },
  });
  
  const getIp = req => {
    return req.headers['x-forwarded-for'];
  };

  Schema.static({
    async record(ctx) {
      const ip = getIp(ctx.request);
      const { url, origin } = ctx;
      if (!ip) return ;
      console.info(ip);
      const item = await this.findOne({ ip, url });
      if (item && Date.now() - item.createdAt.getTime() < 3600000) return false;
      return await this.create({ ip, url, origin });
    },
  });

  return mongoose.model('TongJi', Schema, 'TongJi');
};
